﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using MsForgeReboot.Framework.Entities;
using MsForgeReboot.Framework.Interfaces;
using MsForgeReboot.Framework.Services.Contracts;
using MsForgeReboot.Framework.TownCrierChannels;

namespace MsForgeReboot.Services {
    public class ScheduleDeliveryService : IScheduleDeliveryService {

        private readonly MsForgeContext _context;
        private readonly IList<IChannel> _channels;

        public ScheduleDeliveryService(MsForgeContext c, IChannelListLoader loader) {
            this._context = c;
            this._channels = loader.LoadChannels();
        }


        /// <summary>
        /// Delivers the event through all the channels chosen 
        /// </summary>
        /// <param name="source">Event to deliver</param>
        /// <returns>IList of DeliveryResuls</returns>
        public void ScheduleDelivery(Event source) {

            string cryName = String.Format("Delivery for {0} on {1}", source.Title, DateTime.Now.ToString());
            var users = this._context.Users.Where(u => u.ReceiveNotifications == true).ToList();

            foreach (var user in users) {
                this._channels.Add(new MassMailChannel {
                    MailAddress = user.Username,
                    Source = source
                });
            }

            foreach (var channel in this._channels) {
                channel.Source = source;
                this._context.Cries.Add(new Cry {
                    Name = cryName,
                    Status = CryStatus.Scheduled,
                    Channel = this.SerializeChannel(channel)
                });


            }
            this._context.SaveChanges();

        }

        private byte[] SerializeChannel(IChannel source) {
            BinaryFormatter f = new BinaryFormatter();
            MemoryStream m = new MemoryStream();
            f.Serialize(m, source);
            return m.ToArray();
        }
    }
}
